package com.boesch.electroOffice.presentation.invoice;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ComponentSystemEvent;
import javax.portlet.PortletSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.boesch.electroOffice.business.businessObject.InvoiceBusinessObject;
import com.boesch.electroOffice.business.common.BusinessException;
import com.boesch.electroOffice.dataaccess.common.IllegalDataAccessException;
import com.boesch.electroOffice.model.messerli.Invoice;
import com.boesch.electroOffice.utils.MessageUtils;
import com.boesch.electroOffice.utils.PortletUtils;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

@Controller
@ManagedBean
@SessionScoped
public class InvoiceDetailController implements Serializable {

	private static final long serialVersionUID = -8203782926098575741L;
	private static final Log log = LogFactoryUtil.getLog(InvoiceDetailController.class);
	
	@Autowired
	private InvoiceBusinessObject invoiceBusinessObject;

	private Invoice invoice = new Invoice();
	
	public void loadData(ComponentSystemEvent event) {
		PortletSession session = PortletUtils.getPortletSession();
		String invoiceNumber = String.valueOf(session.getAttribute("invoiceNumber"));
		try {
			invoice = invoiceBusinessObject.readInvoiceByInvoiceNumber(invoiceNumber);
		} catch (IllegalDataAccessException e) {
			MessageUtils.addErrorMessage("Rechnung konnte nicht geladen werden.");
			log.error("Failed to load invoice from database: " + invoiceNumber, e);
		} catch (BusinessException e) {
			MessageUtils.addErrorMessage("Rechnung konnte nicht geladen werden.");
			log.error("Failed to load invoice from database: " + invoiceNumber, e);
		}
	}
	
	public Invoice getInvoice() {
		return invoice;
	}
}
